package demo3;

import java.util.Stack;
class MinStack {
    public Stack<Integer> stack;
    public Stack<Integer> stackTmp;
    public MinStack() {
        stack = new Stack<>();
        stackTmp = new Stack<>();
    }
    //先赋最大值
    public int min = Integer.MAX_VALUE;
    public void push(int val) {
        //有比他小的就赋值
        if(val < min){
            min = val;
        }
        stack.push(val);
    }
    
    public void pop() {
        if(stack.pop() == min){
            //被pop后min需要重新赋值，依旧用最大值
            min = Integer.MAX_VALUE;
            //将所有元素转移到stackTmp，目的是为了让min重新与所有元素比较
            while(!stack.empty()){
                int tmp = stack.pop();
                if(tmp < min){
                    min = tmp;
                }
                stackTmp.push(tmp);
            }
            //再转移到stack
            while(!stackTmp.empty()){
                stack.push(stackTmp.pop());
            }
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return min;
    }
}